package com.mattcofer.cartoonwidget;

import java.lang.reflect.Array;

import com.mattcofer.cartoonwidget.CartoonProvider.Cartoons;
import com.mattcofer.cartoonwidget.CartoonProvider.CartoonsColumns;

import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.app.Activity;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Resources;
import android.text.InputFilter.LengthFilter;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class ConfigureActivity extends Activity implements View.OnClickListener {
	private static final String TAG = "CartoonWidget";

	//UI Widgets
	private Button m_btnSave;
	private Button m_btnClean;
	private Spinner m_spnCartoon;
	
	private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, ".ConfigureActivity$onCreate called");

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.configure);
        
        //Find the UI widgets
        m_btnSave = (Button)findViewById(R.id.configure_save);
        m_btnClean = (Button)findViewById(R.id.button_clean); 

        //Wires up the spinner widget that allows the user to choose the cartoon
        //that this instance of the widget will display
        m_spnCartoon = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.cartoons, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        m_spnCartoon.setAdapter(adapter);
        
        //Wire up the onClick listener
        m_btnSave.setOnClickListener(this);
        
        //Wire up the onClick listener
        m_btnClean.setOnClickListener(m_btnClean_Click_Listener);        
        
        // Read the appWidgetId to configure from the incoming intent
        mAppWidgetId = getIntent().getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        
        setConfigureResult(Activity.RESULT_CANCELED);
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
            return;
        }

    }

    /*
     * Handles the clean button click.  I made this function to try to offer
     * a way to clean up the existing widgets. I am not sure if the widgets listed
     * as bound are supposed to be there or not.  
     */  
    private OnClickListener m_btnClean_Click_Listener = new OnClickListener() {
        public void onClick(View v) {
        	onClick_Clean(v);
        	Toast.makeText(v.getContext(), "Widget clean up complete", 3);
        }
        
    	public void onClick_Clean(View v) {
    		Log.d(TAG, ".ConfigureActivity$m_btnClean_Click_Listener called");
    		ContentResolver resolver = v.getContext().getContentResolver();
            AppWidgetManager manager = AppWidgetManager.getInstance(v.getContext());
            int[] currentAppWidgetIds = manager.getAppWidgetIds(new ComponentName(v.getContext(), CartoonWidget.class));
            
            String activeProviders = "Installed widget providers";
            for (AppWidgetProviderInfo info : manager.getInstalledProviders())
            {
            	activeProviders += ", " + info.provider.toString();
            }
            Log.d(TAG, activeProviders);
            
            for (int appWidgetId : currentAppWidgetIds) {
                Uri appWidgetUri = ContentUris.withAppendedId(Cartoons.CONTENT_URI, appWidgetId);
                
                resolver.delete(appWidgetUri, null, null);
                
                manager.bindAppWidgetId(appWidgetId, null);
                
                Log.d(TAG, ".ConfigureActivity$m_btnClean_Click_Listener deleted widget Uri: " + appWidgetUri.toString());
            }
    	}
    };
	
	public void onClick(View v) {
		Log.d(TAG, ".ConfigureActivity$onClick View: " + v.getId());
        switch (v.getId()) {
	        case R.id.configure_save:
	        {
	        	Log.d(TAG, ".ConfigureActivity$onClick case: R.id.configure_save");
	 			// Picked save, so write values to the database
	        	ContentValues values = new ContentValues();
	        	
	            values.put(BaseColumns._ID, mAppWidgetId);
	            
	            String selectedCartoon = ((String)m_spnCartoon.getSelectedItem());
            	
	            Resources res = this.getResources();
            	String[] cartoonUrls = res.getStringArray(R.array.cartoon_urls);
            	
	            if (selectedCartoon.equalsIgnoreCase("Dilbert"))
	            {
	            	//Dilbert
	            	values.put(CartoonsColumns.URL, cartoonUrls[0]);
	            }
	            else
	            {
	            	//Calvin and Hobbes
	            	values.put(CartoonsColumns.URL, cartoonUrls[1]);
	            }
	            
	            Log.d(TAG, ".ConfigureActivity$onClick AppWidgetsColumns put (url=" + values.getAsString(CartoonsColumns.URL) + ")");
	
	            // TODO: perform METAR lookup as needed, either here or during first update
	            // TODO: update instead of insert if editing an existing widget
	            ContentResolver resolver = getContentResolver();
	            Uri newRowUri = null;
	            newRowUri = resolver.insert(Cartoons.CONTENT_URI, values);
	            if (newRowUri!=null)
	            {
	            	Log.d(TAG, ".ConfigureActivity$onClick ContentResolver inserted values into row: " + newRowUri.toString());
	            }
	            else
	            {
	            	Log.d(TAG, ".ConfigureActivity$onClick ContentResolver failed inserting values into a new row");
	            }
	            
	            // Trigger pushing a widget update to surface
	            UpdateService.requestUpdate(new int[] { mAppWidgetId });
	            
	            Log.d(TAG, ".ConfigureActivity$onClick Called UpdateService.requestUpdate with mAppWidgetId: " + mAppWidgetId);
	            
	            startService(new Intent(this, UpdateService.class));
	            Log.d(TAG, ".ConfigureActivity$onClick Called startService");
	
	            setConfigureResult(Activity.RESULT_OK);
	            Log.d(TAG, ".ConfigureActivity$onClick Called setConfigureResult");
	            finish();
	            Log.d(TAG, ".ConfigureActivity$onClick Called finish()");
	            break;
	        }
	        default:
	        {
	        	Log.d(TAG, ".ConfigureActivity$onClick case unhandled");
	        }
        }
	}

    /**
     * Convenience method to always include {@link #mAppWidgetId} when setting
     * the result {@link Intent}.
     */
    public void setConfigureResult(int resultCode) {
        final Intent data = new Intent();
        data.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
        setResult(resultCode, data);
    }


}
